package cn.edu.bit.lixin.blog.biz;

import java.util.List;

import cn.edu.bit.lixin.blog.dao.BlogDAO;
import cn.edu.bit.lixin.blog.entity.Blog;
import cn.edu.bit.lixin.blog.entity.Category;
import cn.edu.bit.lixin.blog.entity.User;

public class BlogManager {
	public final int PAGE_SIZE = 5;//show how many blogs in one page
	private BlogDAO dao;
	private CateManager cateManager;
	private UserManager userManager;

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public CateManager getCateManager() {
		return cateManager;
	}

	public void setCateManager(CateManager cateManager) {
		this.cateManager = cateManager;
	}

	public BlogDAO getDao() {
		return dao;
	}

	public void setDao(BlogDAO dao) {
		this.dao = dao;
	}
	
	/**
	 * get all the blogs
	 * @return
	 */
	public List<Blog> getBlogs(){
		return dao.findAll("Blog");
	}
	
	/**
	 * 获取当前页的blogs
	 * @param currentPage
	 * @return
	 */
	public List<Blog> getPagedBlogs(int currentPage){
		String hql = "from Blog order by id";
		return dao.pagedQuery(hql, currentPage, PAGE_SIZE);
	}
	
	/**
	 * 获取blog的总数
	 * @return
	 */
	public int getTotalBlogs(){
		return (int) dao.queryForCount("select count(id) from Blog");
	}
	
	/**
	 * 根据id获取特定的日志
	 * @param blogid
	 * @return a specific blog
	 */
	public Blog getSpecificBlog(int blogid){
		return (Blog)dao.findById(Blog.class, blogid);
	}
	
	
	/**
	 * 向数据库中新增一篇日志
	 * @param blogname
	 * @param content
	 * @return
	 */
	public boolean addBlog(String blogname, String content){
		Blog blog = new Blog();
		blog.setBlogname(blogname);
		blog.setPubTime(cn.edu.bit.lixin.blog.util.TimeUtil.getInstance().getNowTime());
		blog.setContent(content);
		
		//得到第一个分类，暂时这样
		//TODO:根据前台传来的分类信息，对日志进行分类设置
		Category cate = cateManager.getSpecificCate(1);
		
		//得到第一个用户，暂时这样
		//TODO:根据前台传来的用户信息，对日志进行作者设置
		User user = userManager.getSpecificUser(1);
		
		blog.setCategory(cate);
		blog.setUser(user);
		
		dao.save(blog);
		return true;
	}
	
	/**
	 * 修改日志
	 * @param blogid
	 * @param blogname
	 * @param content
	 * @return
	 */
	public boolean updateBlog(int blogid, String blogname, String content){
		Blog blog = this.getSpecificBlog(blogid);
		blog.setBlogname(blogname);
		blog.setContent(content);
		try{
			dao.update(blog);
			System.out.println("update success");
			return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 删除指定的日志
	 * @param blogid
	 * @return
	 */
	public boolean deleteBlog(int blogid){
		Blog blog = this.getSpecificBlog(blogid);
		
		try{
			dao.delete(blog);
			return true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
}
